const express = require('express')
const cors = require('cors')
const db = require('./db')
const { getBooks, delBook, addBook } = db

const app = express()

app.listen(3000, () => {
  console.log('http://localhost:3000')
})

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

app.get('/api/getbooks', async (req, res) => {
  const data = await getBooks()
  // console.log(data)
  res.send({
    status: 200,
    msg: '获取图书列表成功',
    data,
  }) 
})

app.get('/api/delbook', async (req, res) => {
  const { id } = req.query
  const data = await delBook(id)
  console.log('await等待的结果', data)
  if (data.affectedRows === 1) {
    res.send({
      status: 200,
      msg: '删除图书成功',
    })
  } else {
    res.send({
      status: 400,
      msg: '删除图书失败',
    })
  }
})

app.post('/api/addbook', async (req, res) => {
  const data = req.body
  const result = await addBook(data)
  console.log('await等待的结果',result)
  if (result.affectedRows === 1) {
    res.send({
      status: 201,
      msg: '添加图书成功！',
    })
  }else {
    res.send({
      status: 400,
      msg: '添加图书失败！',
    })
  }
})
